import React, { useState } from 'react'
import { Form, Input, Button, Toast } from 'antd-mobile'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import "../style/login.scss"
// import {login} 

import Navbar from "../components/Navbar"
import { useNavigate } from 'react-router-dom'
import { login } from '../apis/login'
export default function Login() {

  const [visible, setVisible] = useState(false)
  const [bool, setbool] = useState(true)
  const navigate = useNavigate()

  const onFinish = async (values: any) => {
    // console.log({...values});
    if (values.loginname !== undefined && values.password !== undefined) {
      let res: any = await login(values.loginname, values.password)
      console.log(res);
      switch (res.code) {
        case "200":
          Toast.show({
            content: res.message,
            icon: 'success',
          })
          localStorage.setItem("token",res.data.token)
          localStorage.setItem("userid",res.data.userid)
          localStorage.setItem("username",values.loginname)
          navigate("/index")
          break;

        case "10011":
          Toast.show({
            content: res.message,
            icon: 'fail',
          })
          break;

        default:
          break;
      }
    }

  }
  let fun = (a: any, allValues: any) => {
    if (allValues.loginname !== undefined && allValues.password !== undefined && allValues.password !== "" && allValues.loginname !== "") {
      setbool(false)
    } else {
      setbool(true)
    }
  }

  return (
    <>
      <Navbar title="登录"/>
      <Form requiredMarkStyle='text-required' onFinish={onFinish} onValuesChange={(changedValues, allValues) => fun(changedValues, allValues)}
        footer={
          <>
            <Button block type='submit' color='danger' size='large' shape='rounded' disabled={bool}>
              登录
            </Button>
            <p className='reg' onClick={() => { navigate('/reg') }}>
              手机快速注册
            </p>
          </>
        }>
        <Form.Header>欢迎登陆！</Form.Header>

        <Form.Item name='loginname' label='手机号' rules={[{ required: true }]}>
          <Input placeholder='请输入用户名' clearable autoComplete='false' />
        </Form.Item>

        <Form.Item name='password' label='密码' rules={[{ required: true, message: "请输入正确密码" }]}>
          <div className="password">
            <Input placeholder='请输入密码' clearable type={visible ? 'text' : 'password'} autoComplete='false' />
            <div className='eye'>
              {!visible ? (
                <EyeInvisibleOutline onClick={() => setVisible(true)} />
              ) : (
                <EyeOutline onClick={() => setVisible(false)} />
              )}
            </div>
          </div>
        </Form.Item>
      </Form>
    </>
  )
}
